package com.sesurity.service.Impl;

import com.sesurity.domain.LoginUser;
import com.sesurity.domain.User;
import com.sesurity.service.LoginServcie;
import com.sesurity.utils.JwtUtil;
import com.sesurity.utils.RedisCache;
import com.sesurity.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginServcie {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());

        Authentication authentication=authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authentication)) {
                throw new RuntimeException("用户名或密码错误");
        }

        //使用userid生成token

        LoginUser loginUser= (LoginUser) authentication.getPrincipal();

        String userId=loginUser.getUser().getId().toString();

        String jwt= JwtUtil.createJWT(userId);

        //authenticate存入redis

        redisCache.setCacheObject("login:"+userId,loginUser);


        //把token响应给前端

        HashMap<String,String> map=new HashMap<>();

        map.put("token",jwt);
        return new ResponseResult(200,"登录成功",map);

    }
}
